package com.hrhx.springboot.web;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.hrhx.springboot.domain.Cnarea;
import com.hrhx.springboot.mongodb.repository.CnareaRepository;
import com.hrhx.springboot.mysql.service.CnareaService;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping(value = "/cnarea")
public class CnareaRestController {

	@Autowired
	private CnareaService cnareaService;
	
	@Autowired
	private CnareaRepository cnareaRepository;
	
	/**
	 * 当Mysql请求超时的时候，能够以最快的速度切换到MongoDB
	 */
	private static Boolean isMysqlConnection = true;

	@ApiOperation(value = "获取省级详细信息", notes = "/cnarea/list")
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public List<Cnarea> getAllFirstLevel() {
		List<Cnarea> cnareaList = null;
		if(!isMysqlConnection){
			return cnareaRepository.findByLevel(0);
		}
		try{//默认先执行Mysql
			isMysqlConnection = true;
			cnareaList = cnareaService.getAllFirstLevel();
			System.out.println("Mysql：获取省级详细信息");
		}catch(Exception e){//出现异常用MongoDB	
			isMysqlConnection = false;
			cnareaList = cnareaRepository.findByLevel(0);
			System.out.println("MongoDB：获取省级详细信息");
		}
		return cnareaList;
	}

	@ApiOperation(value = "获取level级以及关联上级的详细信息", notes = "/cnarea/query?id=1&level=1")
	@ApiImplicitParams({
        @ApiImplicitParam(name = "cnarea", value = "地理详细信息", required = false, dataType = "Cnarea")
	})
	@RequestMapping(value = "/query", method = RequestMethod.GET)
	public List<Cnarea> getByParentId(@ModelAttribute Cnarea cnarea) {
		List<Cnarea> cnareaList = null;	
		if(!isMysqlConnection){
			return cnareaRepository.findByLevelAndParentId(cnarea.getLevel(),cnarea.getId());
		}
		try{//默认先执行Mysql
			isMysqlConnection = true;
			cnareaList = cnareaService.getByParentId(cnarea.getLevel(),cnarea.getId());
			System.out.println("Mysql：获取level级以及关联上级的详细信息");
		}catch(Exception e){//出现异常用MongoDB	
			isMysqlConnection = false;
			cnareaList = cnareaRepository.findByLevelAndParentId(cnarea.getLevel(),cnarea.getId());
			System.out.println("MongoDB：获取level级以及关联上级的详细信息");
		}
		System.out.println("获取Level级别："+cnarea.getId());
		System.out.println("获取上级Id："+cnarea.getLevel());
		return cnareaList;
	}

}